package serialize

import (
	"encoding/json"
	"encoding/xml"
	"io"
	"net/url"
	"strings"

	"codeup.aliyun.com/lsxd/zltx/adapter/utils/charset"

	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

// FormGBKDeserializer is a deserializer for form data with GBK encoding.
func FormGBKDeserializer(data []byte, v any) error {
	utf8, err := charset.GbkToUtf8(data)
	if err != nil {
		return err
	}

	values, err := url.ParseQuery(string(utf8))
	if err != nil {
		return err
	}

	v = values
	return nil
}

// FormDeserializer is a deserializer for form data.
func FormDeserializer(data []byte, v any) error {
	values, err := url.ParseQuery(string(data))
	if err != nil {
		return err
	}

	v = values
	return nil
}

// JSONGBKDeserializer is a deserializer for JSON data with GBK encoding.
func JSONGBKDeserializer(data []byte, v any) error {
	utf8, err := charset.GbkToUtf8(data)
	if err != nil {
		return err
	}
	return json.Unmarshal(utf8, v)
}

// XMLGBKDeserializer is a deserializer for XML data with GBK encoding.
func XMLGBKDeserializer(data []byte, v any) error {
	decoder := xml.NewDecoder(strings.NewReader(string(data)))
	decoder.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
		return transform.NewReader(input, simplifiedchinese.GBK.NewDecoder()), nil
	}
	return decoder.Decode(v)
}

// XMLDeserializer is a deserializer for XML data.
func XMLDeserializer(data []byte, v any) error {
	return xml.Unmarshal(data, v)
}
